package cn.stylefeng.guns.sys.modular.system.service;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.sys.modular.system.entity.BtyBorrowerFlowInformation;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyBorrowerFlowInformationMapper;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 档案管理表 服务实现类
 * </p>
 *
 * @author liuy
 * @since
 */
@Service
public class BtyBorrowerFlowInformationService extends ServiceImpl<BtyBorrowerFlowInformationMapper, BtyBorrowerFlowInformation> {
    /**
     * 获取档案管理列表
     */
    @Resource
    private BtyBorrowerService btyBorrowerService;

    public Page<Map<String, Object>> list(String condition, String month, String status) {
        Page page = LayuiPageFactory.defaultPage();

        return this.baseMapper.list(page, condition, month, status);
    }

    public Page<Map<String, Object>> listSearch(String borrowerId, String beginTime, String endTime) {
        Page page = LayuiPageFactory.defaultPage();

        return this.baseMapper.listSearch(page, borrowerId, beginTime, endTime);
    }

    /**
     * 获取所有未还款金额
     */
    public Double allMoney() {
        return this.baseMapper.allOldMoney() + this.baseMapper.allNewMoney();
    }

    public List<BtyBorrowerFlowInformation> borrowerInfo() {
        return baseMapper.borrowerInfo();
    }

    public List<BtyBorrowerFlowInformation> listByBorrowerId(String borrowerId) {
        return baseMapper.listByBorrowerId(borrowerId);
    }

    public int insertFq(Long id, String borrowerId, String loanDate, String bj, String yll, String month, String hkje, String lx, Date createTime, Long userId, String summary) {
        return baseMapper.insertFq(id, borrowerId, loanDate, bj, yll, month, hkje, lx, createTime, userId, summary);
    }


    public int updateByIds(String[] ids) {
        return baseMapper.updateByIds(ids);
    }

    /**
     * 导入还款金额excel
     */
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public Boolean batchImport(String fileName, MultipartFile file) throws Exception {
        boolean notNull = false;
        List<BtyBorrowerFlowInformation> userList = new ArrayList<>();
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw new Exception("上传文件格式不正确");
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }

        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        //excel中多个sheet表，获取所有sheet表的数量
        int sheets = wb.getNumberOfSheets();
        for (int i = 0; i < sheets; i++) {
            Sheet sheet = wb.getSheetAt(i);
            if (sheet != null) {
                notNull = true;
            }
            for (int r = 1; r <= sheet.getLastRowNum(); r++) {
                Row row = sheet.getRow(r);
                if (row == null) {
                    continue;
                }
                //获取单元格
                Cell cell = row.getCell(4);
                if (ToolUtil.isNotEmpty(cell)) {
                    cell.setCellType(CellType.STRING);
                }
                String yhkje = row.getCell(4) == null ? "" : row.getCell(4).getStringCellValue();
                String name = row.getCell(9) == null ? "" : row.getCell(9).getStringCellValue();
                String summary = row.getCell(10) == null ? "" : row.getCell(10).getStringCellValue();
                if (yhkje != null && !"".equals(yhkje) && !"0".equals(yhkje)) {
                    if ("殷世峰".equals(name)) {
                        name = "伦志超";
                    }
                    List<BtyBorrowerFlowInformation> btyBorrower = this.baseMapper.selectByName(name);
                    if (btyBorrower.size() > 0) {
                        selectByName(yhkje, btyBorrower);
                    } else {
                        List<BtyBorrowerFlowInformation> btyBorrowers = this.baseMapper.borrowerInfo();
                        for (int j = 0; j < btyBorrowers.size(); j++) {
                            if (summary.contains("滕艳杰")) {
                                summary = "王雷";
                            }
                            String xm = btyBorrowers.get(j).getName();
                            if (summary.contains(xm)) {

                                btyBorrower = this.baseMapper.selectByName(xm);
                                if (btyBorrower.size() > 0) {
                                    selectByName(yhkje, btyBorrower);
                                }
                            }
                        }
                    }
                }
            }
        }
        return notNull;
    }

    /**
     * 公共方法
     */
    public int selectByName(String yhkje, List<BtyBorrowerFlowInformation> btyBorrower) {
        BigDecimal ayhkje = new BigDecimal(yhkje);
        BigDecimal money = new BigDecimal(String.format("%.2f", new BigDecimal(btyBorrower.get(0).getHkje()).add(new BigDecimal(btyBorrower.get(0).getLx()))));
        BigDecimal[] bigDecimals = ayhkje.divideAndRemainder(money);
        int bs = Integer.parseInt(bigDecimals[0].stripTrailingZeros().toString());
        if (bs > 0) {
            int ys = Integer.parseInt(bigDecimals[1].toPlainString().substring(0, bigDecimals[1].toPlainString().indexOf(".")));
            if ((ys == 0 || ys == 100 || ys <= 1)) {
                for (int j = 0; j < bs; j++) {
                    BtyBorrowerFlowInformation btyBorrow = new BtyBorrowerFlowInformation();
                    btyBorrow.setId(btyBorrower.get(j).getId());
                    btyBorrow.setYhkje(yhkje);
                    btyBorrow.setFlag(1);
                    this.baseMapper.updateYhkjes(btyBorrow);
                }
            }
        }
        return 1;
    }

}
